package com.awenhui.demo.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author yuxf
 * @version 1.0
 * @date 2020/5/6 11:18
 */
public class EncryptionUtils {

    static Logger logger = LoggerFactory.getLogger(EncryptionUtils.class);

    /**
     * MD5加密
     *
     * @param str 要加密的字符串
     * @return
     */
    public static String Md5(String str) {
        try {
            byte[] digest = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF8"));
            int i;
            StringBuilder sb = new StringBuilder();
            for (int offset = 0; offset < digest.length; offset++) {
                i = digest[offset];
                if (i < 0) i += 256;
                if (i < 16) sb.append(0);
                sb.append(Integer.toHexString(i));//通过Integer.toHexString方法把值变为16进制
            }
            return sb.toString();


        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(EncryptionUtils.Md5("123456"));
        System.out.println(EncryptionUtils.Md5("123456a"));
    }
}
